package top.buaarobot.webserver.web.rest;

import com.alibaba.fastjson.JSONObject;
import top.buaarobot.webserver.domain.Comment;
import top.buaarobot.webserver.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/api/comment")
public class CommentResource {
    @Autowired
    private CommentService commentService;

    @PostMapping("/get")
    public Iterable<Comment> GetComment(@RequestBody JSONObject json) {
        String type = json.getString("type");
        int fatherId = json.getIntValue("fatherId");
        int commentId = json.getIntValue("commentId");
        int userId = json.getIntValue("userId");
        if(fatherId != 0){                      // 需拿取的为某内容下的一级评论
            System.out.println("[POST /api/comment/get]: " + type + fatherId + "的评论");
            return commentService.GetByFatherId(fatherId);
        }else if(commentId != 0){               // 需拿取的为评论的回复
            System.out.println("[POST /api/comment/get]: 评论"+commentId+"的回复");
            return commentService.GetByCommentId(commentId);
        }else {                                 // 需拿取某用户的评论
            System.out.println("[POST /api/comment/get]: 用户"+userId+"的评论");
            return commentService.GetByUserId(userId);
        }
    }

    @PostMapping("/add")
    public String AddComment(@RequestBody JSONObject json) {
        Comment comment = (Comment) JSONObject.toJavaObject(json, Comment.class);
        System.out.println("[POST /api/comment/add]: "+json.getString("content"));
        return this.commentService.AddComment(comment);
    }

    @PostMapping("/update")
    public String UpdateComment(@RequestBody JSONObject json) {
        int id = json.getIntValue("id");
        String content = json.getString("content");
        System.out.println("[POST /api/comment/update]: 评论id:"+id);
        return this.commentService.UpdateComment(id, content);
    }

    @PostMapping("/delete")
    public String DeleteComment(@RequestBody JSONObject json) {
        int id = json.getIntValue("id");
        System.out.println("[POST /api/comment/delete]: 评论id:"+id);
        return this.commentService.DeleteComment(id);
    }
}